package com.eva.config.loaders;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eva.dao.system.SystemConfigMapper;
import com.eva.dao.system.model.SystemConfig;
import com.eva.framework.cache.CacheProxy;
import com.eva.framework.config.SystemConfigHelper;
import com.eva.framework.config.model.SystemConfigCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * v5.1.0整体调整
 */
@Slf4j
@Component
public class SystemConfigCacheLoader {

    @Resource
    private SystemConfigMapper systemConfigMapper;

    @Resource
    private CacheProxy<String, Map<String, SystemConfigCache>> cacheProxy;

    /**
     * 加载到缓存
     *
     * @param force 是否强制加载
     */
    public void loadToCache (boolean force) {
        this.loadToCache(null, force);
    }

    /**
     * 加载到缓存
     *
     * @param dataScope 数据作用域，取值为application-config.yml中的id，为空时将自动读取id值
     * @param force 是否强制加载
     */
    public void loadToCache (String dataScope, boolean force) {
        // v5.1.0，调整cacheKey的获取方式
        SystemConfigHelper configHelper = SystemConfigHelper.build(dataScope);
        String cacheKey = configHelper.getCacheKey();
        log.info("开始加载 {} 系统配置至缓存", configHelper.getDataScope());
        if (!force && cacheProxy.get(cacheKey) != null) {
            log.debug("系统配置数据已加载至缓存，跳过本次加载！");
            return;
        }
        QueryWrapper<SystemConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                // v5.1.0，scope字段更改为scopes
                .like(SystemConfig::getScopes, "," + configHelper.getDataScope() + ",")
                .eq(SystemConfig::getDeleted, Boolean.FALSE);
        List<SystemConfig> configs = systemConfigMapper.selectList(queryWrapper);
        // 转为缓存对象列表
        List<SystemConfigCache> configCaches = new ArrayList<>();
        for (SystemConfig config : configs) {
            SystemConfigCache configCache = new SystemConfigCache();
            BeanUtils.copyProperties(config, configCache);
            configCaches.add(configCache);
        }
        // 转为map结构
        Map<String, SystemConfigCache> configMap = new HashMap<>();
        for (SystemConfigCache configCache : configCaches) {
            configMap.put(configCache.getCode(), configCache);
        }
        // 存入缓存
        cacheProxy.put(cacheKey, configMap);
        log.info("系统配置缓存完成，共加载 {} 条配置记录", configMap.size());
    }
}
